import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * This class implements {@link DataStorage} and it saves the data in a csv file
 * using a {@link CSVCustomerSerializer}.
 */
public class CSVFile implements DataStorage {
	private final CSVCustomerSerializer customerSerializer;
	private final String fileName;

	public CSVFile() {
		customerSerializer = new DefaultCSVCustomerSerializer(";");
		fileName = "CustomerManagement.csv";
	}

	public CSVFile(CSVCustomerSerializer customerSerializer, String fileName) {
		this.customerSerializer = customerSerializer;
		this.fileName = fileName;
	}

	
	/**
	 * Save List of Customer objects using a BufferedWriter.
	 * 
	 * @param customers
	 * 		List of customers which has to be saved.
	 */
	@Override
	public boolean saveCustomers(List<Customer> customers) {
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));

			writer.append(customerSerializer.serializeCustomers(customers));

			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * Load List of Customer objects by parsing content of
	 * fileName.
	 * 
	 * @return
	 * 		List containing Customer objects
	 */
	@Override
	public List<Customer> loadCustomers() {
		ArrayList<Customer> customers = new ArrayList<Customer>();
		if (new File(fileName).exists()) {
			try {
				BufferedReader reader = new BufferedReader(new FileReader(
						fileName));

				String line = null;
				// we go thourgh every line of the file

				while ((line = reader.readLine()) != null) {
					if (!line.equals("")) {
						// and now we parse the line using the
						// customerSerializer which returns an customer object.
						// We add this object to our list
						customers.add(customerSerializer.readLine(line));
					}
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return customers;
	}

	public CSVCustomerSerializer getCSVCustomerSerializer() {
		return customerSerializer;
	}

	public String getFileName() {
		return fileName;
	}
}
